//
//  HOTMessageBoxViewController.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-9-11.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTMessageBoxViewController.h"
#import "HOTMessageBoxCell.h"
#import "HOTMessageChatViewController.h"

@interface HOTMessageBoxViewController () <HOTMessageBoxCellDelegate, ZZZPopupViewDelegate>{
    
    BOOL isEdit;
    
    NSMutableArray *_dataList;
    NSMutableArray *_selItemList;
    UIBarButtonItem *_editBarBtnItem;
    UIBarButtonItem *_cancelBarBtnItem;
    UIBarButtonItem *_delBarBtnItem;
    UIBarButtonItem *_backBarBtnItem;
    
    NSInteger _pageNo;
}
@property(nonatomic,strong)NSMutableArray *dataList;
@end

@implementation HOTMessageBoxViewController

@synthesize dataList = _dataList;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setNaviTitle:@"メッセージBOX"];
    
    
    //[self addRightBtnTarget:self action:@selector(barEditBtnClicked:) image:[UIImage imageNamed:@"btn_edit_off"] hImage:[UIImage imageNamed:@"btn_edit_on"]];
    
    _backBarBtnItem = self.navigationItem.leftBarButtonItem;
    
    _tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_message"]];
    
    _editBarBtnItem = [self createBarButtomItemTarget:self action:@selector(barEditBtnClicked:) image:[UIImage imageNamed:@"btn_edit_off"] hImage:[UIImage imageNamed:@"btn_edit_on"] edgeInsets:UIEdgeInsetsMake(0, 0, 0, -20)];
    
    
    _cancelBarBtnItem = [self createBarButtomItemTarget:self action:@selector(barCancelBtnClicked:) image:[UIImage imageNamed:@"btn_cancel_off"] hImage:[UIImage imageNamed:@"btn_cancel_on"] edgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
    
    _delBarBtnItem = [self createBarButtomItemTarget:self action:@selector(barDelBtnClicked:) image:[UIImage imageNamed:@"btn_delete_off"] hImage:[UIImage imageNamed:@"btn_delete_on"] edgeInsets:UIEdgeInsetsMake(0, 0, 0, -20)];
    
    self.navigationItem.rightBarButtonItem = _editBarBtnItem;
    
#if 0
    
    NSArray *tempArr = @[@{@"title":@"ゆーじ", @"isMailOpen":@"0"},
                  @{@"title":@"ゆーじゆーじゆーじゆーじゆーじ1", @"isMailOpen":@"1"},
                  @{@"title":@"ゆーじ2", @"isMailOpen":@"0"},
                  @{@"title":@"ゆーじ3", @"isMailOpen":@"2"},
                  @{@"title":@"ゆーじ4", @"isMailOpen":@"0"},
                  @{@"title":@"ゆーじ5", @"isMailOpen":@"1"},
                  @{@"title":@"ゆーじ6", @"isMailOpen":@"2"},
                  @{@"title":@"ゆーじ7", @"isMailOpen":@"0"},
                  @{@"title":@"ゆーじ8", @"isMailOpen":@"0"},
                  @{@"title":@"ゆーじ9", @"isMailOpen":@"1"},
                  @{@"title":@"ゆーじ10", @"isMailOpen":@"0"},
                  @{@"title":@"ゆーじ11", @"isMailOpen":@"2"},
                  @{@"title":@"ゆーじ12", @"isMailOpen":@"0"},
                  @{@"title":@"ゆーじ13", @"isMailOpen":@"1"},
                  @{@"title":@"ゆーじ14", @"isMailOpen":@"2"},
                  @{@"title":@"ゆーじ15", @"isMailOpen":@"0"},
                  @{@"title":@"ゆーじ16", @"isMailOpen":@"0"},
                  @{@"title":@"ゆーじ17", @"isMailOpen":@"1"}];
    
    _dataList = [NSMutableArray arrayWithArray:tempArr];
    
    NSArray *tempList = @[@NO,@NO,@NO,@NO,@NO,@NO,@NO,@NO,@NO,@NO,@NO,@NO,@NO,@NO,@NO,@NO,@NO,@NO];
    
    _selItemList = [[NSMutableArray alloc] initWithCapacity:_dataList.count];
    for (int i =0; i < _dataList.count; i++) {
        
        [_selItemList addObject:@"0"];
    }

#else
    _selItemList = [NSMutableArray array];
    self.dataList = [NSMutableArray array];
    
    _tableView.showFooter = YES;
    _tableView.showHeader = YES;
    
    __unsafe_unretained HOTMessageBoxViewController *tempObj = self;
    _tableView.headerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo = 1;
        [tempObj requestDataFromNet];
    };
    
    _tableView.footerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo ++;
        [tempObj requestDataFromNet];
    };
    
    _pageNo = 1;
    [self requestDataFromNet];
    
#endif
}

#pragma mark - UItableView DataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellId = @"cellID";
    HOTMessageBoxCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil) {
        
        UINib *nib = [UINib nibWithNibName:XIB(@"HOTMessageBoxCell") bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellId];
        
        cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.delegate = self;
    cell.indexPath = indexPath;

    NSDictionary *dic = [self.dataList objectAtIndex:indexPath.row];
    
    NSString *status = [dic objectForKey:@"conv_status"];
    
    [cell setEdit:isEdit animated:NO];
    cell.dateTimeLabel.text = [dic objectForKey:@"last_msg_time"];
    cell.titleLabel.text = [dic objectForKey:@"user_nick"];
    [cell setMailStatus:status];
    
    NSString *selFlgStr = [_selItemList objectAtIndex:indexPath.row];
    BOOL selFlg = NO;
    if ([selFlgStr isEqualToString:@"1"]) {
        
        selFlg = YES;
    }
    [cell setSelectedItem:selFlg];

    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataList.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 62;
}

#pragma mark - UITableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = [self.dataList objectAtIndex:indexPath.row];
    HOTMessageChatViewController *mcvc = [[HOTMessageChatViewController alloc] initWithNibName:@"HOTMessageChatViewController" bundle:nil conv_type:CONV_TYPE_OTHER target_uid:[dic objectForKey:@"user_id"]];
    
    
    [self.navigationController pushViewController:mcvc animated:YES];
}

-(void)selectedItem:(BOOL)selected indexPath:(NSIndexPath *)indexPath {
    
    if (selected) {
        
        [_selItemList replaceObjectAtIndex:indexPath.row withObject:@"1"];
    } else {
        [_selItemList replaceObjectAtIndex:indexPath.row withObject:@"0"];
    }
}

-(void)barEditBtnClicked:(id)sender {
    
    isEdit = YES;
    
    [self setTableViewEdit:isEdit];

    [self.navigationItem setLeftBarButtonItem:_cancelBarBtnItem animated:YES];
    [self.navigationItem setRightBarButtonItem:_delBarBtnItem animated:YES];

}

-(void)barCancelBtnClicked:(id)sender {
    
    [self.navigationItem setLeftBarButtonItem:_backBarBtnItem animated:YES];
    [self.navigationItem setRightBarButtonItem:_editBarBtnItem animated:YES];
    
    isEdit = NO;
    
    [self setTableViewEdit:isEdit];
}

-(void)barDelBtnClicked:(id)sender {
    
    ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                          message:MSG_IS_CONFIRM
                                                         delegate:self
                                                cancelButtonTitle:ALERT_BTN_CANCEL
                                                 otherButtonTitle:ALERT_BTN_OK];
    popupView.tag = 101;
    [popupView showInWindow];
    
    
}

-(void)refrashTableAfterDelete {
    
    NSMutableArray *delIndexPathArr = [NSMutableArray array];
    NSMutableArray *delObjArr = [NSMutableArray array];
    for (int i = 0; i < _selItemList.count; i ++) {
        
        NSString *selStr = [_selItemList objectAtIndex:i];
        
        if ([selStr isEqualToString:@"1"]) {
            //选中的item
            [delObjArr addObject:[_dataList objectAtIndex:i]];
            //[_dataList removeObjectAtIndex:i];
            NSIndexPath *delIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
            
            [delIndexPathArr addObject:delIndexPath];
        }
    }
    [_dataList removeObjectsInArray:delObjArr];
    _selItemList = [NSMutableArray array];
    for (int i =0; i < _dataList.count; i ++) {
        
        [_selItemList addObject:@"0"];
    }
    
    if (delIndexPathArr.count > 0) {
        
        [_tableView deleteRowsAtIndexPaths:delIndexPathArr withRowAnimation:UITableViewRowAnimationLeft];
    }
    
    isEdit = NO;
    [self setTableViewEdit:isEdit];
    
    [self.navigationItem setLeftBarButtonItem:_backBarBtnItem animated:YES];
    [self.navigationItem setRightBarButtonItem:_editBarBtnItem animated:YES];
    
    [_tableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.5];
}

-(void)setTableViewEdit:(BOOL)flg {
 
    NSArray *cells = [_tableView visibleCells];
    
    for (HOTMessageBoxCell *cell in cells) {
        
        [cell setEdit:flg animated:YES];
    }
}

-(void)delDataWithArray:(NSArray *)convIdList {
    
    [self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_CONV_ID:[NSString stringWithFormat:@"%@", [convIdList componentsJoinedByString:@","]]};
    
    __unsafe_unretained HOTMessageBoxViewController *tempObj = self;
    [self requestWithURL:HOT_URL_MESSAGE_DEL Parameters:parameters success:^(NSInteger result, NSArray * dataArr) {
        
        [tempObj loadingSuccess];
        
        [self refrashTableAfterDelete];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(void)requestDataFromNet {
    
    [self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_P_NUM:@(_pageNo),
                                 REQ_KEY_P_SIZE:kPageCnt};
    
    __unsafe_unretained HOTMessageBoxViewController *tempObj = self;
    [self requestWithURL:HOT_URL_USER_MY_MSG Parameters:parameters success:^(NSInteger result, NSArray * dataArr) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if (dataArr.count == 0) {
            
            if (_pageNo == 1) {
                
                [tempObj.dataList removeAllObjects];
                [_selItemList removeAllObjects];
                [_tableView reloadData];
                [self alertNoDataMessage:^{
                    //[tempObj.navigationController popViewControllerAnimated:YES];
                }];
            } else {
                [self alertNoDataAgainMessage:nil];
            }
            
            
            return;
        }
        
        if (_pageNo == 1) {
            [_selItemList removeAllObjects];
            [tempObj.dataList removeAllObjects];
        }
        for (int i=0; i < dataArr.count; i ++) {
            //初始化
            [_selItemList addObject:@"0"];
        }
        
        [tempObj.dataList addObjectsFromArray:dataArr];
        
        [_tableView reloadData];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}


-(void)backBtnClicked:(id)sender {
    
    if (self.navigationController.viewControllers.count == 1) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)popupView:(ZZZPopupView *)popupView buttonKind:(ZZZPopupViewBtnKind)btnKind {
    [super popupView:popupView buttonKind:btnKind];
    if (popupView.tag == 101 && btnKind == ZZZPopupViewConfirmBtnKind) {
        //点击删除按钮的场合
        NSMutableArray *delObjArr = [NSMutableArray array];
        for (int i = 0; i < _selItemList.count; i ++) {
            
            NSString *selStr = [_selItemList objectAtIndex:i];
            
            if ([selStr isEqualToString:@"1"]) {
                //选中的item
                NSDictionary *itemDic = [_dataList objectAtIndex:i];
                
                [delObjArr addObject:[HOTUtils getString:[itemDic objectForKey:@"conv_id"]]];
            }
        }
        
        if (delObjArr .count > 0) {
            
            [self delDataWithArray:delObjArr];
        }
    }
}

@end
